/**
 * sh4tistory - Syntax Highlighter for Tistory
 * - http://sh4tistory.googlecode.com
 *
 * Copyright (c) 2012 Kwiyong Roh (kwiyong.roh@gmail.com).
 * Released under the MIT license
 * - http://opensource.org/licenses/mit-license.php
 *
 * Based on:
 * SyntaxHighlighter - http://alexgorbatchev.com/SyntaxHighlighter/
 * Hay Krane's jsDynaLoad() - http://github.com/hay/jsdynaload
 * tsyntax - http://tsyntax.googlecode.com
 * ddoong2's blog - http://ddoong2.com/601
 */

window.shSetup = window.shSetup || {};

shSetup.jQueryURL = shSetup.jQueryURL || 'http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.4.min.js';
shSetup.shBrushURL = shSetup.shBrushURL || 'http://sh4tistory.googlecode.com/git/lib/syntaxhighlighter/scripts/';
shSetup.shStyleURL = shSetup.shStyleURL || 'http://sh4tistory.googlecode.com/git/lib/syntaxhighlighter/styles/';

shSetup.theme = shSetup.theme || '';
shSetup.theme = shSetup.theme ? 'shCore' + shSetup.theme + '.css' : 'shCoreDefault.css';

// JS, CSS dynamic loader
var $include = function(files, onComplete) {

	onComplete = onComplete || function() {};  // Callback is not required

	var getFileExtension = function(fileName) {
		var ext = /^.+\.([^.]+)$/i.exec(fileName.toLowerCase());
		return ext == null ? '' : ext[1];
	};

	function includeFile(file, callBackInc) {
		callBackInc = callBackInc || function() {};  // Callback is not required

		var fileRef = null;
		var ext = getFileExtension(file);

		if (ext == 'js') {
			fileRef = document.createElement('script');
			fileRef.type = 'text/javascript';
			fileRef.src = file;
		} else if (ext == 'css') {
			fileRef = document.createElement('link');
			fileRef.type = 'text/css';
			fileRef.rel = 'stylesheet';
			fileRef.href = file;
		} else { return; }

		if (fileRef.readyState) {  // for IE
			fileRef.onreadystatechange = function() {
				// IE sometimes gives back the one state, and sometimes the other,
				// so we need to check for both
				if (fileRef.readyState === 'loaded' || fileRef.readyState == 'complete') {
					fileRef.onreadystatechange = null;
					callBackInc();
				}
			};
		} else {  // for Non-IE
			fileRef.onload = function() { callBackInc(); };
		}

		// Adding to the <head> is safer than the end of the <body>
		document.getElementsByTagName('head')[0].appendChild(fileRef);
	};  // end of includeFile

	if (typeof files === 'string') {  // Used for loading one single file
		includeFile(files, onComplete);
	} else if (files instanceof Array) {  // Load an array of files
		var i = 0, l = files.length;

		function includeCallBack() {
			if (i >= l) {  // Execute the original callback
				onComplete();
				return false;
			}

			includeFile(files[i], includeCallBack);
			i++;
		};

		includeCallBack();
	}

};  // end of $include

//SyntaxHighlighter path config
var patchBrushPath = function() {
	var args = arguments, result = [];
	for ( var i = 0; i < args.length; i++) {
		result.push(args[i].replace('@', shSetup.shBrushURL));
	}
	return result;
};

var filesArray = new Array();
if (typeof jQuery != 'function') { filesArray.push(shSetup.jQueryURL); }
filesArray.push(shSetup.shStyleURL + shSetup.theme);
filesArray.push(shSetup.shBrushURL + 'shCore.js');
filesArray.push(shSetup.shBrushURL + 'shAutoloader.js');

$include(filesArray, function(){

	(function() {  // jQuery container
		jQuery.noConflict();
		jQuery(document).ready(function($) {  // jQuery block
		//==================================================

			$('blockquote').each(function() {

				var starter = '###';
				var $this = $(this);

				// 공백과 의미없는 줄바꿈을 제외한 첫 문자가 '###'일 경우
				if ( $.trim($this.text().replace(/\n/gi, '')).substring(0,3) == starter ) {

					// 복사 붙여넣기 했을 때 탭 처리
					$this.find('span[class*=Apple-tab-span]').replaceWith(function() {
						return $(this).text();
					});

					// 편집창에서 직접 수정했을 때 탭 처리
					$this.find('p[style*=margin-left]').each(function() {
						var $elem = $(this);
						var style = $elem.attr('style');
						var result = /\s*?margin-left:\s(\w+?)em;\s*?/gi.exec(style);
						if (result != null) {
							result = result[1];
						}
						var spaceCount = parseInt(result) * 2;
						var spaceString = '';
						for ( var i = 0; i < spaceCount; i++) {
							spaceString += '&nbsp;';
						}
						$elem.removeAttr('style');
						$elem.html(spaceString + $elem.html());
					});

					var temp = $this.html();

					// p, br 태그 처리
					temp = temp.replace(/\n/gi, '');
					temp = temp.replace(/<p><\/p>/gi, '');
					temp = temp.replace(/<p><br\s*\/?><\/p>/gi, '\n');		// 줄바꿈
					temp = temp.replace(/<P>(.*?)<\/P>/gi, '$1\n');			// 한줄끝
					temp = temp.replace(/<br\s*\/?>/gi, '\n');				// 줄바꿈

					// 문자열 라인단위 분리
					temp = temp.split('\n');

					var shBrush = $.trim(temp[0].replace(starter, 'brush: '));

					temp.shift();
					temp = temp.join('\n');

					temp = '<pre class="' + shBrush + '">\n' + temp + '\n</pre>';

					// blockquote를 pre로 치환
					$this.replaceWith(temp);

				}  // end of if block '###'

			});  // end of 'blockquote'

			SyntaxHighlighter.autoloader.apply(null, patchBrushPath(
				'applescript			@shBrushAppleScript.js',
				'actionscript3 as3		@shBrushAS3.js',
				'bash shell				@shBrushBash.js',
				'coldfusion cf			@shBrushColdFusion.js',
				'cpp c					@shBrushCpp.js',
				'c# c-sharp csharp		@shBrushCSharp.js',
				'css					@shBrushCss.js',
				'delphi pascal pas		@shBrushDelphi.js',
				'diff patch				@shBrushDiff.js',
				'erl erlang				@shBrushErlang.js',
				'groovy					@shBrushGroovy.js',
				'java					@shBrushJava.js',
				'jfx javafx				@shBrushJavaFX.js',
				'js jscript javascript	@shBrushJScript.js',
				'perl pl				@shBrushPerl.js',
				'php					@shBrushPhp.js',
				'text plain				@shBrushPlain.js',
				'powershell ps			@shBrushPowerShell.js',
				'py python				@shBrushPython.js',
				'ruby rails ror rb		@shBrushRuby.js',
				'sass scss				@shBrushSass.js',
				'scala					@shBrushScala.js',
				'sql					@shBrushSql.js',
				'vb vbnet				@shBrushVb.js',
				'xml xhtml xslt html	@shBrushXml.js'
			));

			SyntaxHighlighter.defaults['auto-links'] = false;
			SyntaxHighlighter.defaults['toolbar'] = false;
			SyntaxHighlighter.defaults['tab-size'] = 4;

			SyntaxHighlighter.all();

		//==================================================
		});  // end of jQuery block
	})();  // end of jQuery container

});